<?php
/*
 * FileServiceReportUpload.php
 * Upload a service report submitted by FileServiceReport.html
 *
 * Copyright 2012 Eugene Mah <eugenem@hadron>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 */

require('functions.inc');

/*
 * Establish a connection to the database using PDO. Most of this is
 * taken from PHP in Action by Reiersol, Baker, Shiflett (Manning Publications)
 * and the PHP PDO documentation (http://php.net/manual/en/book.pdo.php)
 */
try {
  $conn = new PDO(
    'mysql:dbname=ComplianceReports;host=localhost',
    'rad','tfFxn2Tley');
}
catch (Exception $e) {
  throw new Exception($e->getMessage());
}
// Set PDO to throw more exceptions when encountered
$conn->setAttribute(PDO::ATTR_ERRMODE,
                    PDO::ERRMODE_EXCEPTION);

/* Set the destination for the uploaded files. Files will be uploaded into
 * a subdirectory of this based on the year of the survey
 */
$uploaddir = "ServiceReports/";
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
  <title>Service Report Upload</title>
  <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  <meta name="generator" content="Geany 1.22" />
</head>

<body>
  <h1>Radiological Equipment Database</h1>

<?php
// Get the Survey ID from the _POST variable
$surveyID = strip_tags($_POST['surveyID']);

// Get the work order number associated with this report
$WONum = strip_tags($_POST['WONum']);

// Check the database to see if this surveyID exists in the database
$query_surveyID = $conn->prepare(
  "SELECT count(*) FROM TestDates where SurveyID = :surveyID");
$query_surveyID->bindParam(':surveyID', $surveyID);
$query_surveyID->execute();

if ($query_surveyID->fetchColumn()<1) {
  // Exit if there were no results
  exit("<p>Survey ID " . $surveyID . " doesn't exist in the database!'</p>");
}

// Get the year associated with this survey ID
$query_survYr = $conn->prepare("SELECT YEAR(TestDate) FROM TestDates WHERE SurveyID=:SurveyID");
$query_survYr->bindParam(':SurveyID',$surveyID);
$query_survYr->execute();
$survYr = $query_survYr->fetchColumn();

// Append the year to $uploaddir. This is where the service report will be uploaded to.
$uploaddir .= $survYr . "/";

// Process the uploaded file
// Was a file uploaded?
if ($_FILES['ServiceReport']['error'] === UPLOAD_ERR_OK) {
  // A file was uploaded
  // Prepend $surveyID to the file name and move to $uploaddir
  $uploadFile = $uploaddir . $surveyID . "_" . basename($_FILES['ServiceReport']['name']);
  // Check to make sure a file doesn't exist already
  if (file_exists($uploadFile)) {
    echo "<p>Can't upload file. Duplicate file name already exists</p>";
    exit();
  }
  // We only want PDF files. Check and make sure what was uploaded was a PDF
  if (!($finfo = finfo_open(FILEINFO_MIME))) {
    echo "<p>Unable to open magic file database</p>";
    finfo_close($finfo);
    exit();
  }
  $ftype = split(";",finfo_file($finfo, $_FILES['ServiceReport']['tmp_name']));
  if ($ftype[0] == "application/pdf") {
    // Uploaded file is a PDF. Move it to $uploaddir
      if (move_uploaded_file($_FILES['ServiceReport']['tmp_name'], $uploadFile) == false) {
        echo "<p>File upload failed</p>";
      }
      else {
        echo "<p>Service report for ". $surveyID . " has been uploaded. Updating database.</p>";
        // Update the recommendations for this survey ID
        $query_updateRecs = $conn->prepare(
          "UPDATE Recommendations SET ServiceReportPath = :uploadFile,
           WONum = :WONum
           WHERE SurveyID = :surveyID");
        $query_updateRecs->bindParam(':uploadFile', $uploadFile, PDO::PARAM_STR);
        $query_updateRecs->bindParam(':surveyID', $surveyID, PDO::PARAM_INT);
        $query_updateRecs->bindParam(':WONum', $WONum, PDO::PARAM_INT);
        if ($query_updateRecs->execute()) 
          echo "<p>Database update successful.</p>\n";
        else 
          echo "<p>Database update failed.</p>\n";
      }
  }
  else {
    echo "<p>Uploaded file is not a PDF</p>";
    exit();
  }
  finfo_close($finfo);
}
else {
  echo "<p>No file was uploaded.</p>";
  exit();
}
?>
<p><a href="index.html" target="_top" >Main</a></p>

</body>

</html>
